package com.sejong.andproject2;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{

	public static String SENDER_ID = "236895394554";


	String c2dm_msg = null;
	
	public GCMIntentService() {
	super(SENDER_ID);
	}
	
	private static final String TAG = "===GCMIntentService===";
	
	public void onReceive(Context context, Intent intent) {
	   
	}
	
	
	@Override
	protected void onRegistered(Context arg0, String registrationId) {
	Log.i(TAG, "Device registered: regId = " + registrationId);
	}
	
	@Override
	protected void onUnregistered(Context arg0, String arg1) {
	Log.i(TAG, "unregistered = "+arg1);
	}
	
	@Override
	protected void onMessage(Context arg0, Intent arg1) {
	Log.i(TAG, "CONTEXT : = " + arg0);
	
	   if (arg1.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
	    
	    
	    c2dm_msg = arg1.getExtras().getString("msg");
	    GET_GCM();
	    Log.i(TAG, "new message= "+ c2dm_msg);
	    //Log.i(TAG,c2dm_msg);
	    
	   }
	
	}
	
	public void GET_GCM() { 
	    
	    Thread thread = new Thread(new Runnable() { 
	        public void run() { 
	        	
	        handler.sendEmptyMessage(0); 
	        } 
	    }); 
	    thread.start(); 
	} 
	
	private Handler handler = new Handler() { 
	    public void handleMessage(Message msg) { 
	                    	
	        Context context = getApplicationContext();
	        int duration = Toast.LENGTH_LONG;
	        
	        Toast toast = Toast.makeText(context, c2dm_msg, duration);
	        toast.setGravity(Gravity.CENTER, 0, 0);
	        
	        toast.show(); 
	        c2dm_msg = null;
	
	    } 
	    };
	
	public void showMsg(String msg, int option) 
	   { 
	Toast.makeText(this, msg, option).show(); 
	}
	@Override
	protected void onError(Context arg0, String errorId) {
	Log.i(TAG, "Received error: " + errorId);
	}
	
	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
	return super.onRecoverableError(context, errorId);
	}
	}
